<?php
class HelpController extends AppController {
    // var $helpers = array ('Html','Form');
    //errore:
    var $name = 'Help'; // riferimento alla cartella delle view
    
    public function beforeFilter(){
		parent::beforeFilter();
        $this->Auth->allow('index','save');
    	Controller::loadModel('Help');
    }
	
	public function beforeRender(){
		// print_r($this->viewVars['help']);die;
		// if(isset($this->viewVars['help']) && isset($this->viewVars['help']['HelpLang'])){
			// foreach ($this->viewVars['help']['HelpText'] as $key => $helpText) {
				// $this->viewVars['help']['HelpText'][$helpText['lang']]=$helpText;
				// unset($this->viewVars['help']['HelpText'][$key]);
			// }
		// }
		// if(isset($this->viewVars['helps'])){
			// $helps=array();
			// foreach ($this->viewVars['helps'] as $key => $help) {
				// if (isset($helps[$help['codice']])) {
// 					
				// } else {
// 					
				// }
				// $this->viewVars['help']['HelpText'][$help['lang']]=$help;
// 				
				// unset($this->viewVars['help']['HelpText'][$key]);
			// }
		// }
		
	}

    public function index() {

    	// $joins = array("joins"=>array(
    						   // array("table"=>"categories","alias"=>"Category", "type" => "LEFT", "conditions" => array("Category.id = Help.categories_id"))
							   // ,array("table" => "categories_lang","alias" => "CategoryLang","type" => "LEFT", "conditions" => array("Category.id = CategoryLang.reference_id"))
							   // ,array("table"=>"help_lang","alias"=>"HelpLang", "type" => "LEFT", "conditions" => array("Help.id = HelpLang.reference_id"))
							   // )
					// );
		// $recursive = array("recursive"=>-1);
		// $order = array("order" => "Help.codice");
    	// $this->set('helps', $this->Help->find('all', array_merge($recursive,$order)));
    	Controller::loadModel('Dual');
    	$sql = "select Help.codice, count(*) rowspan from help Help group by Help.codice";
		// print_r($this->Dual->query($sql));die;
		$result = $this->Dual->query($sql);
		$rowspan = array();
		foreach ($result as $value) {
			$rowspan[$value["Help"]["codice"]]=$value["0"]["rowspan"];
		}
		// print_r($rowspan);die;
		$sql = "select Help.id, Help.codice, CategoryLang.name, HelpLang.titolo, HelpLang.testo, Help.pubblicato, Help.dt_ins";
		$sql .= " from help Help inner join help_lang HelpLang on Help.id=HelpLang.reference_id and HelpLang.locale='". Configure::read("Config.language") ."'";
		$sql .= " left join categories Category on Help.categories_id=Category.id";
		$sql .= " inner join categories_lang CategoryLang on Category.id = CategoryLang.reference_id and CategoryLang.locale='". Configure::read("Config.language") ."'";
		$sql .= " order by Help.codice";
		$helps = $this->Help->query($sql);
		// print_r($helps);die;
		foreach ($helps as $key => $help) {
			if (isset($rowspan[$help["Help"]["codice"]])) {
				$helps[$key]["Help"]["rowspan"]=$rowspan[$help["Help"]["codice"]];
				unset($rowspan[$help["Help"]["codice"]]);
			} else {
				$helps[$key]["Help"]["rowspan"]=0;
			}
		}
		// print_r($helps);die;
    	$this->set('helps', $helps);
    }
	
	public function add($areaTematica=null,$codiceHelp=null) {
		$this->set("categories",$this->getCategories($codiceHelp));
		$help = array();
		if (empty($areaTematica)) {
		    Controller::loadModel('Parametro');
			$this->Parametro->set("codice","area_tematica_default");
			$this->Parametro->read();
			// $this->Parametro->findByCodice("area_tematica_default");	
			$areaTematicaDefault = $this->Parametro->field("valore");
			// print_r($this->Parametro);
			$help["Help"]["categories_id"]=$areaTematicaDefault;
		} else {
			$help["Help"]["categories_id"]=$areaTematica;
		}
		$help["Help"]["codice"]=$codiceHelp;
		// print_r($help);
		$this->set('help', $help);
		// $this->render("/Help/edit");		
		// $this->redirect("/Help/edit");
	}

    public function edit($id=0) {
    	
		$this->Help->id = $id;
		$this->set('help', $this->Help->read());
		$this->set("categories",$this->getCategories($this->Help->field("codice")));

    }

	private function getCategories($codiceHelp="") {
		// verifico il gruppo configurato sui parametri, in caso contrario restituisco un warning
	    Controller::loadModel('Parametro');
		$this->Parametro->set("codice","area_tematica");
		$this->Parametro->read();
		$areaTematica = $this->Parametro->field("valore");
		if (empty($areaTematica)) {
			$this->Session->setFlash(__("Attenzione! il parametro di configurazione area tematica non è stato impostato."),null,null,LOG_WARNING);
		}
    	Controller::loadModel('Category');
        // $this->Category->read($areaTematica);
        // $this->Category->read(3);
    	$this->Category->hasOne['Help']['conditions'] = array('Help.codice' => $codiceHelp);
        $categories = $this->Category->children($areaTematica); 
		foreach ($categories as $key => $category) {
			if ($category["Category"]["lft"]+1 <> $category["Category"]["rght"]) {
				unset($categories[$key]);
			}
		}
		// print_r($categories);
		return $categories; 		
	}

    public function delete($id='') {
		if ($id=='')
			$id = $this->request->data['id'];
		$this->Help->delete($id);
		$this->Session->setFlash(__('Help cancellato.'));
		$this->redirect("/Help");
    }
	
	public function save() {
		    $ds = $this->Help->getDataSource();
			$ds->begin();
		    try {
				$this->Help->setUtente($this->Auth->user());
			    $this->Help->save($this->request->data);
				$ds->commit();
				$this->Session->setFlash(__("Help Aggiornato."));
		    } catch (exception $e) {
		    	if (isset($ds)) {
		    		$ds->rollback();
		    	}
		    	CakeLog::error($e->getMessage());
				$this->Session->setFlash(__("Help non aggiornato:"). $e->getMessage(),null,null,LOG_ERR);
		    }
		if (isset($this->Help->id)) {
			$this->redirect("/Help/edit/".$this->Help->id);
		} else {
			$this->redirect($this->referer());
		}
	}

}
?>